/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package justdoit.view;

import java.text.ParseException;
import javax.swing.event.ChangeEvent;
import justdoit.view.model.PriorityComboBoxModel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.swing.*;
import javax.swing.event.ChangeListener;
import justdoit.controller.LanguageManager;
import justdoit.controller.TaskManager;
import justdoit.model.Task;
import justdoit.model.User;

/**
 * The is the Dialog for showing/editing one Task.
 * It can be a new Task or a existing task. Should be inherited for special use.
 * @author Can
 */
public class TaskDialog extends JDialog {

    private final int defaultWidth = 350;
    private final int defaultHeight = 350;
    // components
    // infoPanel contains inputPanel and messagePanel
    // inputPanel contains everything about input
    // messagePanel contains the error message for the user
    private JPanel infoPanel;
    private JPanel inputPanel;
    private JPanel messagePanel;
    private JPanel actionPanel;
    // input
    private JLabel descriptionLabel;
    private JTextField descriptionInput;
    private JLabel categoryLabel;
    private JComboBox categoryComboBox;
    private JLabel deadlineLabel;
    private JTextField deadlineInput;
    private JComboBox deadlineComboBox;
    private JLabel priorityLabel;
    private JComboBox priorityComboBox;
    private JLabel progressLabel;
    //private JTextField progressInput;
    private JSlider progressSlider;
    private JLabel reminderLabel;
    private JTextField reminderInput;
    private JCheckBox reminderCheckBox;
    private JComboBox reminderComboBox;
    private JLabel reminderDummyGap;
    private String[] reminderOptions = {LanguageManager.getString("combo.reminder.before5Minutes"), LanguageManager.getString("combo.reminder.before15Minutes"), LanguageManager.getString("combo.reminder.before1Hour")};/*{"today", "tomorrow", "in a week", "in 5 hours"}*/

    Calendar dueDate;
    Calendar reminderDate = null;
    // action
    private JButton okButton;
    private JButton cancelButton;
    // message
    private JLabel messageLabel;

    public TaskDialog(String title) {
        initComponents(title);
        addActionListeners();
    }

    protected Task getTaskFromInterface(Task task) {
        if (categoryComboBox.getSelectedItem() != null) {
            task.setCategory(categoryComboBox.getSelectedItem().toString());
        }
        task.setPriority(((PriorityComboBoxModel) priorityComboBox.getModel()).getSelectedPriority());
        task.setDescription(descriptionInput.getText());
        //task.setProgress(Integer.parseInt(progressInput.getText()));
        task.setProgress(progressSlider.getValue());
        task.setDeadLine(deadlineComboBox.getSelectedItem().toString());
        task.setReminder(reminderInput.getText());
        task.setDueDate(dueDate);
        task.setReminderDate(reminderDate);
        return task;
    }

    protected final void updateInterfacebyTask(Task task) {
        descriptionInput.setText(task.getDescription());
        deadlineInput.setText(task.getDeadLine());
        categoryComboBox.setSelectedItem(task.getCategory());
        priorityComboBox.setSelectedItem(task.getDisplayPriority());
        priorityComboBox.updateUI();
        // progressInput.setText(task.getProgress().toString());
        progressSlider.setValue(task.getProgress());
        progressLabel.setText(LanguageManager.getString("label.progress") + " \"" + progressSlider.getValue() + "%\"");
        reminderInput.setText(task.getReminder());
    }

    protected void okAction() {
        this.dispose();
    }

    protected void cancelAction() {
        this.dispose();
    }

    protected void insertToActionPanel(Component c, int index) {
        this.actionPanel.add(c, index);
    }

    protected void showMessage(String message) {
        this.messageLabel.setText(message);
    }

    // return 0 if success, -1 if failed
    protected int validation() {
        if (descriptionInput.getText().trim().isEmpty()) {
            showMessage(LanguageManager.getString("showMessage.taskInfo"));
            descriptionInput.requestFocus();
            descriptionInput.selectAll();
            return -1;
        }
        if (!deadlineInput.getText().trim().isEmpty()) {
            String deadline = deadlineInput.getText().trim();
            // TODO: do some validation about deadline
        }
//        if (!reminderInput.getText().trim().isEmpty()) {
//            String reminderString = reminderInput.getText().trim();
//            System.out.println("reminderString = " + reminderString);
//            User user = TaskManager.getCurrentUser();
//            DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, user.getLocale());
//            try {
//                Date date = df.parse(reminderString);
//                System.out.println(date.toString());
//            } catch (ParseException ex) {
//                System.out.println(ex.getMessage());
//                String standardFormatString = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, user.getLocale()).format(new Date());
//                String message = LanguageManager.getString("showMessage.reminderInfo") + " " + standardFormatString;
//                showMessage(message);
//                reminderInput.requestFocus();
//                reminderInput.selectAll();
//                return -1;
//            }
//        }
        return 0;
    }

    private void initComponents(String title) {
        //========================================== Input Panel
        // line 1
        descriptionLabel = new JLabel(LanguageManager.getString("label.taskName"));
        descriptionInput = new JTextField(20);
        descriptionInput.setToolTipText(LanguageManager.getString("tooltip.description"));
        // line 2
        categoryLabel = new JLabel(LanguageManager.getString("label.taskCategory"));
        List<String> allCategories = TaskManager.getAllCategories();
        if (allCategories == null || allCategories.isEmpty()) {
            categoryComboBox = new JComboBox();
        } else {
            categoryComboBox = new JComboBox(allCategories.toArray());
        }
        categoryComboBox.setToolTipText(LanguageManager.getString("tooltip.category"));
        categoryComboBox.setEditable(true);
        // line 3
        deadlineLabel = new JLabel(LanguageManager.getString("label.taskDate"));
        //deadlineInput = new JTextField(LanguageManager.getString("dateFormat"), 20);
        deadlineInput = new JTextField(20);
        deadlineInput.setToolTipText(LanguageManager.getString("tooltip.date"));

        String[] dueDates = {LanguageManager.getString("combo.dueDate.today"), LanguageManager.getString("combo.dueDate.tomorrow"), LanguageManager.getString("combo.dueDate.inAWeek"), LanguageManager.getString("combo.dueDate.in5Hours"), LanguageManager.getString("dateFormat")};
        deadlineComboBox = new JComboBox(dueDates);
        deadlineComboBox.setToolTipText(LanguageManager.getString("tooltip.date"));
        deadlineComboBox.setEditable(false); //here is important, change it /shadone
        // line 4
        priorityLabel = new JLabel(LanguageManager.getString("label.taskPriority"));
        priorityComboBox = new JComboBox(new PriorityComboBoxModel());
        priorityComboBox.setToolTipText(LanguageManager.getString("tooltip.priority"));
        // line 5
        progressLabel = new JLabel(LanguageManager.getString("label.progress"));

        //progressInput = new JTextField("0", 10);
        progressSlider = new JSlider(0, 100, 0);
        progressLabel.setText(LanguageManager.getString("label.progress") + " \"" + progressSlider.getValue() + "%\"");
        progressSlider.setToolTipText(LanguageManager.getString("tooltip.progress"));
        // line 6
        reminderLabel = new JLabel(LanguageManager.getString("label.reminder"));
        reminderInput = new JTextField(20);
        reminderInput.setToolTipText(LanguageManager.getString("tooltip.reminder"));
        reminderCheckBox = new JCheckBox();
        reminderDummyGap = new JLabel();
        reminderComboBox = new JComboBox(reminderOptions);
        //futuristic part begins
        //reminderComboBox.setEditable(true);
        reminderComboBox.setVisible(false);
        //futuristic part ends
        inputPanel = new JPanel(new GridLayout(7, 2, 10, 10));
        // line 1
        inputPanel.add(descriptionLabel);
        inputPanel.add(descriptionInput);
        // line 2
        inputPanel.add(deadlineLabel);
        inputPanel.add(deadlineComboBox);
        // line 3
        inputPanel.add(categoryLabel);
        inputPanel.add(categoryComboBox);
        // line 4
        inputPanel.add(priorityLabel);
        inputPanel.add(priorityComboBox);
        // line 5
        inputPanel.add(progressLabel);
        //inputPanel.add(progressInput);
        inputPanel.add(progressSlider);
        // line 6
        inputPanel.add(reminderLabel);
        inputPanel.add(reminderCheckBox);
        //line 7
        inputPanel.add(reminderDummyGap);
        inputPanel.add(reminderComboBox);

        //========================================== Message Panel
        messageLabel = new JLabel(LanguageManager.getString("showMessage.enterInfo"));
        messageLabel.setSize(defaultWidth, 10);
        messageLabel.setForeground(Color.red);
        messagePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        messagePanel.add(messageLabel);

        //========================================== Info Panel
        infoPanel = new JPanel(new BorderLayout(10, 10));
        infoPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        infoPanel.add(BorderLayout.CENTER, inputPanel);
        infoPanel.add(BorderLayout.SOUTH, messagePanel);

        //========================================== Action Panel
        okButton = new JButton(LanguageManager.getString("button.ok"));
        cancelButton = new JButton(LanguageManager.getString("button.cancel"));
        actionPanel = new JPanel(new FlowLayout());
        actionPanel.add(okButton);
        actionPanel.add(cancelButton);

        this.setLayout(new BorderLayout());
        this.add(BorderLayout.CENTER, infoPanel);
        this.add(BorderLayout.SOUTH, actionPanel);

        // focus and other improvement
        // descriptionInput.requestFocus();

        this.getRootPane().setDefaultButton(okButton);

        // Hide on Close
        this.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
        this.setSize(defaultWidth, defaultHeight);
        this.setTitle(title);
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setModal(true);
    }

    private void addActionListeners() {
        progressSlider.addChangeListener(new ChangeListener() {

            public void stateChanged(ChangeEvent e) {
                progressLabel.setText(LanguageManager.getString("label.progress") + " \"" + progressSlider.getValue() + "%\"");
            }
        });

        cancelButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                cancelAction();
            }
        });

        okButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                okAction();
            }
        });

        reminderCheckBox.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (reminderCheckBox.isSelected() == true) {
                    reminderComboBox.setVisible(true);
                } else {
                    reminderComboBox.setVisible(false);
                }
            }
        });

        deadlineComboBox.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (deadlineComboBox.getSelectedItem().toString().compareTo(LanguageManager.getString("dateFormat")) == 0) {
                    deadlineComboBox.setEditable(true);
                    deadlineComboBox.requestFocus();
                } else {
                    deadlineComboBox.setEditable(false);
                }
                // here if i will have time, i will put them into a calendar class, now im putting everything here
                //shadone
                String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; /*"yyyy-MM-dd HH:mm:ss"*/
                SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
                Calendar now = Calendar.getInstance();
                if (deadlineComboBox.getSelectedItem().toString().compareTo(LanguageManager.getString("combo.dueDate.tomorrow")) == 0) {
                    dueDate = (Calendar) now.clone();
                    dueDate.add(Calendar.DAY_OF_YEAR, +1);
                    System.out.print("  Due date is: " + sdf.format(dueDate.getTime()));
                } else if (deadlineComboBox.getSelectedItem().toString().compareTo(LanguageManager.getString("combo.dueDate.inAWeek")) == 0) {
                    dueDate = (Calendar) now.clone();
                    dueDate.add(Calendar.DAY_OF_YEAR, +7);
                    System.out.print("  Due date is: " + sdf.format(dueDate.getTime()));
                } else if (deadlineComboBox.getSelectedItem().toString().compareTo(LanguageManager.getString("combo.dueDate.in5Hours")) == 0) {
                    dueDate = (Calendar) now.clone();
                    dueDate.add(Calendar.HOUR, +5);
                    System.out.print("  Due date is: " + sdf.format(dueDate.getTime()));
                }

            }
        });

        reminderComboBox.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                // here if i will have time, i will put them into a calendar class, now im putting everything here
                //shadone
                String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; /*"yyyy-MM-dd HH:mm:ss"*/
                SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
                if (reminderComboBox.getSelectedItem().toString().compareTo(LanguageManager.getString("combo.reminder.before5Minutes")) == 0) {
                    reminderDate = (Calendar) dueDate.clone();
                    reminderDate.add(Calendar.MINUTE, -5); //UNDONE!!
                    System.out.print("  Reminder time is: " + sdf.format(reminderDate.getTime()));
                } else if (reminderComboBox.getSelectedItem().toString().compareTo(LanguageManager.getString("combo.reminder.before15Minutes")) == 0) {
                    System.out.print(dueDate.toString());
                    reminderDate = (Calendar) dueDate.clone();
                    reminderDate.add(Calendar.MINUTE, -15);
                    System.out.print("  Reminder time is: " + sdf.format(reminderDate.getTime()));
                } else if (reminderComboBox.getSelectedItem().toString().compareTo(LanguageManager.getString("combo.reminder.before1Hour")) == 0) {
                    reminderDate = (Calendar) dueDate.clone();
                    reminderDate.add(Calendar.HOUR_OF_DAY, -1);
                    System.out.print("  Reminder time is: " + sdf.format(reminderDate.getTime()));
                }

            }
        });


        this.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    okAction();
                } else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    cancelAction();
                }
                super.keyPressed(e);
            }
        });
    }

    public Calendar getReminderDate2(){
        return reminderDate;
    }

    public String getReminderDate() {
        String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; /*"yyyy-MM-dd HH:mm:ss"*/
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        return sdf.format(reminderDate.getTime());
    }

    public void setBackgroundColor(Color color) {
        this.setBackground(color);
    }
}
